package com.autoconfigure.redis.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.cache.CacheKeyPrefix;

/**
 * @author lemon
 * @version 1.0
 * @description: 缓存 key 前缀生成策略
 * @date Create by lemon on 2020-07-10 14:37
 */
public class DefaultCacheKeyPrefix implements CacheKeyPrefix {
    @Value("${spring.app.cache.redis.namespace:}")
    private String namespace;

    @Value("${spring.app.cache.redis.keyDelimiter::}")
    private String keyDelimiter;

    /**
     * Compute the prefix for the actual {@literal key} stored in Redis.
     *
     * @param cacheName will never be {@literal null}.
     * @return never {@literal null}.
     */
    @Override
    public String compute(String cacheName) {
        if (StringUtils.isBlank(this.namespace)) {
            if (StringUtils.isBlank(cacheName)) {
                return "";
            }

            return cacheName + this.keyDelimiter;
        }

        if (StringUtils.isBlank(cacheName)) {
            return this.namespace + this.keyDelimiter;
        }

        return this.namespace + this.keyDelimiter + cacheName + this.keyDelimiter;
    }
}
